package hander

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"path/filepath"
	"user/api/request"
	"user/consts"
	"user/internal/dao"
	"user/internal/model"
	"user/internal/queue"
	"user/pkg"
)

func Register(c *gin.Context) {
	var req request.RegisterReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"msg":  "验证失败",
			"code": 500,
			"data": err.Error(),
		})
		return
	}
	u := model.User{
		Name:     req.Name,
		Sex:      req.Sex,
		Gift:     req.Gift,
		JoinTime: req.JoinTime,
		OutTime:  req.OutTime,
		Num:      req.Num,
	}
	dao.Create(&u)
	queue.PublishPub("Register", &u)
	c.JSON(http.StatusOK, gin.H{
		"msg":  "OK",
		"code": 200,
		"data": "Register",
	})
}

func Login(c *gin.Context) {
	var req request.LoginReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"msg":  "验证失败",
			"code": 500,
			"data": err.Error(),
		})
		return
	}
	var user model.User
	dao.GetOneById(req.Id, &user)
	if user.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"msg":  "用户不存在",
			"code": 500,
			"data": nil,
		})
		return
	}
	token, _ := pkg.NewJWT(consts.JWT_KEY).CreateToken(pkg.CustomClaims{
		ID: user.Id,
	})
	c.JSON(http.StatusOK, gin.H{
		"msg":  "OK",
		"code": 200,
		"data": token,
	})
}

func List(c *gin.Context) {
	var user []model.User
	dao.Find(&user)
	c.JSON(http.StatusOK, gin.H{
		"msg":  "OK",
		"code": 200,
		"data": user,
	})
}

func Upload(c *gin.Context) {
	file, _ := c.FormFile("image")
	ext := filepath.Ext(file.Filename)
	if ext != "png" && ext != "jpg" {
		c.JSON(http.StatusOK, gin.H{
			"msg":  "格式在不正确",
			"code": 500,
			"data": nil,
		})
		return
	}
}
